<template>
	<view class="common-bg">
		<!-- #ifdef APP -->
		<!-- app 这里为什么要两个nav-bar -->
		<uni-nav-bar :border="false" color="#222" backgroundColor="transparent" title="" />
		<!-- #endif -->
		<uni-nav-bar :border="false" color="#222" backgroundColor="transparent" left-icon="left" leftText=""
			:rightText="$t('messageList.allRead')" :title="$t('messageList.title')" @clickLeft="clickLeft"
			@clickRight="clickRight" />
		<view class="pad-20">
			<view class="message-list">
				<view class="item" v-for="(item, index) in messageList" :key="index">
					<view class="item-con">
						<view class="time font-12 col-000-4">
							{{formatRelativeTime(item.create_time)}}
							<!-- //2025-09-23T05:00:00.000Z -->
						</view>
						<view class="left">
							<image v-if="item.type === 'device_share' " class="img" src="/static/svg/share.svg" mode="widthFix">
							</image>
							<uni-icons v-else-if="item.type === 2" color="#30A44F" type="checkbox-filled" size="30"></uni-icons>
							<uni-icons v-else-if="item.type === 3" type="clear" color="#666" size="30"></uni-icons>
							<uni-icons
								v-else-if="item.type === 'device_status' || item.type === 'firmware_update' || item.type ==='pattern_update' || item.type=== 'system' "
								type="info" color="#999" size="30"></uni-icons>
						</view>
						<view class="right">
							<view class="font-16 font-500 col-000-8">
								{{item.title}}
							</view>
							<view class="font-14 font-500 col-000-8 m-t-8">
								{{item.content}}
							</view>
						</view>
					</view>
					<view class="item-btn" v-if="item.type === 'device_share' && item.data && item.data.share_id">
						<!-- 待处理状态：显示接受/拒绝按钮 -->
						<template v-if="item.data.share_status === 0 || item.data.share_status === undefined">
							<view class="flex-center-center btn resolve col-000-8" @click="acceptShare(item)">
								接受
							</view>
							<view class="flex-center-center btn reject col-fff" @click="rejectShare(item)">
								拒绝
							</view>
						</template>
						
						<!-- 已接受状态 -->
						<view v-else-if="item.data.share_status === 1" class="status-text accepted">
							已接受
						</view>
						
						<!-- 已拒绝状态 -->
						<view v-else-if="item.data.share_status === 2" class="status-text rejected">
							已拒绝
						</view>
						
						<!-- 已撤销状态 -->
						<view v-else-if="item.data.share_status === 3" class="status-text revoked">
							已撤销
						</view>
						
						<!-- 已过期状态 -->
						<view v-else-if="item.data.share_status === 4" class="status-text expired">
							已过期
						</view>
					</view>
				</view>
			</view>
			<view class="empty-box" v-if="messageList.length == 0">
				<view class="">
					<view class="empty-img">
						<image class="img-100" src="/static/svg/empty.svg" mode="widthFix"></image>
					</view>
					<view class="empty-text">
						{{ $t('messageList.noMsg') }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uniNavBar from '@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue';
	import messageApi from '@/api/message';
	import shareApi from '@/api/share';
	import {
		formatRelativeTime
	} from '@/common/utils';

	export default {
		components: {
			uniNavBar
		},
		data() {
			return {
				params: {
					page: 1,
					limit: 20,
					total: 0
				},
				contentText: {
					contentdown: "轻轻上拉",
					contentrefresh: "加载中",
					contentnomore: "没有更多数据了",
				},
				messageList: [],
				messageList1: [{
						type: 1,
						title: '设备分享邀请',
						desc: '李四 邀请您共同使用“书房沙画机”',
						time: '2分钟前'
					},
					{
						type: 2,
						title: '邀请已接受',
						desc: '您已成功加入 李四 的设备共享',
						time: '2分钟前'
					},
					{
						type: 3,
						title: '邀请已拒绝',
						desc: '您已拒绝此设备分享邀请',
						time: '2分钟前'
					},
					{
						type: 4,
						title: '系统通知',
						desc: '您的设备“客厅沙画机”已完成固件更新，新',
						time: '2分钟前'
					}
				]
			}
		},
		created() {
			this.contentText.contentdown = this.$t('loadContentText.contentdown');
			this.contentText.contentrefresh = this.$t('loadContentText.contentrefresh');
			this.contentText.contentnomore = this.$t('loadContentText.contentnomore');
			this.getList()
		},
		onReachBottom() {
			this.getList();
		},
		onPullDownRefresh() {
			this.resetSearch()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			formatRelativeTime,
			resetSearch() {
				this.messageList = [];
				this.params.page = 1;
				this.params.limit = 20;
				this.getList()
			},
			getList() {
				let pageNo = this.params.page;
				let pageSize = this.params.limit;
				let totalpage = this.params.total;
				if (totalpage + 1 <= (pageNo - 1) * pageSize) {
					this.loadStatus = "nomore";
					return;
				}
				this.loadStatus = "loading";
				messageApi.getList(this.params).then(res => {
					console.log(res)
					if (res.errCode == 0) {}
					this.messageList = this.messageList.concat(res.list);
					this.params.total = res.total;
					this.params.page = res.page + 1;
					this.loadStatus = "loadmore";
				})
			},
			clickLeft() {
				uni.navigateBack(-1)
			},
			clickRight() {
				console.log('全部已读')
				let ids = this.messageList.map(item => item.message_id);
				if (ids.length > 0) {
					messageApi.batchMarkAsRead(ids).then(res => {
						// 刷新列表
						this.resetSearch()
					})
				}
			},
			
			// 接受分享邀请
			async acceptShare(message) {
				if (!message.data || !message.data.share_id || !message.data.invite_code) {
					uni.showToast({
						title: '分享信息不完整',
						icon: 'none'
					})
					return
				}
				
				try {
					uni.showLoading({
						title: '处理中...'
					})
					
					// 调用接受分享API
					const res = await shareApi.acceptShare({
						shareId: message.data.share_id,
						inviteCode: message.data.invite_code
					})
					
					uni.hideLoading()
					
					if (res.errCode === 0) {
						// 标记消息为已读
						await messageApi.markAsRead(message.message_id)
						
						uni.showToast({
							title: '接受分享成功',
							icon: 'success'
						})
						
						// 刷新消息列表
						setTimeout(() => {
							this.resetSearch()
						}, 1000)
					} else {
						uni.showToast({
							title: res.errMsg || '接受分享失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('接受分享失败:', error)
					uni.showToast({
						title: error.errMsg || '接受分享失败',
						icon: 'none'
					})
				}
			},
			
			// 拒绝分享邀请
			async rejectShare(message) {
				if (!message.data || !message.data.share_id) {
					uni.showToast({
						title: '分享信息不完整',
						icon: 'none'
					})
					return
				}
				
				uni.showModal({
					title: '拒绝分享',
					content: '确定要拒绝此设备分享邀请吗？',
					success: async (modalRes) => {
						if (modalRes.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								})
								
								// 调用拒绝分享API
								const res = await shareApi.rejectShare({
									shareId: message.data.share_id,
									rejectReason: '用户拒绝'
								})
								
								uni.hideLoading()
								
								if (res.errCode === 0) {
									// 标记消息为已读
									await messageApi.markAsRead(message.message_id)
									
									uni.showToast({
										title: '已拒绝分享',
										icon: 'success'
									})
									
									// 刷新消息列表
									setTimeout(() => {
										this.resetSearch()
									}, 1000)
								} else {
									uni.showToast({
										title: res.errMsg || '拒绝分享失败',
										icon: 'none'
									})
								}
							} catch (error) {
								uni.hideLoading()
								console.error('拒绝分享失败:', error)
								uni.showToast({
									title: error.errMsg || '拒绝分享失败',
									icon: 'none'
								})
							}
						}
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.message-list {
		width: 100%;
		margin-top: 80rpx;

		.item-con {
			display: flex;
			align-items: flex-start;
			justify-content: flex-start;
		}

		.item-btn {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			margin-top: 48rpx;

			.btn {
				width: 120rpx;
				height: 68rpx;
				background: #FFFFFF;
				border-radius: 8rpx;
				border: 1px solid rgba(0, 0, 0, 0.8);
				margin-left: 24rpx;

				&.reject {
					background: #000000;
				}
			}
			
			.status-text {
				font-size: 28rpx;
				font-weight: 500;
				padding: 16rpx 32rpx;
				border-radius: 8rpx;
				
				&.accepted {
					color: #30A44F;
					background: rgba(48, 164, 79, 0.1);
				}
				
				&.rejected {
					color: #999999;
					background: rgba(153, 153, 153, 0.1);
				}
				
				&.revoked {
					color: #FF6B6B;
					background: rgba(255, 107, 107, 0.1);
				}
				
				&.expired {
					color: #CCCCCC;
					background: rgba(204, 204, 204, 0.1);
				}
			}
		}

		.item {
			padding: 28rpx 40rpx;
			position: relative;
			margin-bottom: 32rpx;
			background: #FFFFFF;
			box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.08);
			border-radius: 16rpx;

			.left {
				width: 40rpx;
				min-width: 40rpx;
				height: 40rpx;
				margin-right: 46rpx;

				.img {
					width: 36rpx;
					height: 36rpx;
				}
			}

			.time {
				position: absolute;
				right: 40rpx;
				top: 40rpx;
			}
		}
	}
</style>